//
//  BookPageViewController.m
//  DaDa
//
//  Created by User on 15/6/2.
//  Copyright (c) 2015年 User. All rights reserved.
//

#import "BookPageViewController.h"
#import "PageViewController.h"
#import "AppDelegate.h"
#import <MarqueeLabel.h>
@interface BookPageViewController ()<UIPageViewControllerDataSource,UIPageViewControllerDelegate,UIAlertViewDelegate,UITextFieldDelegate>

@property (nonatomic, strong) NSArray *dataArray;

@property (nonatomic, strong) UIPageViewController *pageController;
@property (nonatomic, assign) NSUInteger mIndex;
@property (nonatomic, strong) UITextField *pageTextField;

@end

@implementation BookPageViewController

- (id)initWithBookID:(NSString *)idString
{
    self = [super init];
    if(self)
    {
        _idString = idString;
        [self setHidesBottomBarWhenPushed:YES];
    }
    return self;
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
   [[NSNotificationCenter defaultCenter]removeObserver:self];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [[UIApplication sharedApplication]setStatusBarStyle:UIStatusBarStyleLightContent];
    self.view.backgroundColor = [UIColor whiteColor];
    MarqueeLabel *mLabel = [[MarqueeLabel alloc]initWithFrame:CGRectMake(0, 0, 400, 44)];
    mLabel.text = self.title;
    mLabel.textColor = [UIColor whiteColor];
    mLabel.font = [UIFont boldSystemFontOfSize:20];
    mLabel.textAlignment = NSTextAlignmentCenter;
    self.navigationItem.titleView = mLabel;
    
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[[UIImage imageNamed:@"icon_back_thin"] imageWithRenderingMode:(UIImageRenderingModeAlwaysOriginal)] style:(UIBarButtonItemStylePlain) target:self action:@selector(back)];
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"" style:(UIBarButtonItemStylePlain) target:nil action:nil];

    _mIndex = 0;
    [self getData];
}
- (void)back{
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)getData{
    NSDictionary *dict =  @{@"ebookId" : _idString};
    [AppGlobalClass PostDataWithNSstring:BOOK_DETAILS_URL withDictionary:dict success:^(NSDictionary *dictionary){
        
        NSArray *dataArray = [dictionary objectForKey:@"responseData"];
        NSDictionary *dataDict = [dataArray firstObject];
        
        _dataArray = [[[dataDict objectForKey:@"rows"] firstObject] objectForKey:@"content"];
        
        NSDictionary * options = [NSDictionary dictionaryWithObject:[NSNumber numberWithInteger:UIPageViewControllerSpineLocationMin] forKey:UIPageViewControllerOptionSpineLocationKey];
        
        _pageController = [[UIPageViewController alloc]initWithTransitionStyle:(UIPageViewControllerTransitionStylePageCurl) navigationOrientation:(UIPageViewControllerNavigationOrientationHorizontal) options:options];
        _pageController.dataSource = self;
        _pageController.delegate = self;
        [_pageController.view setFrame:self.view.bounds];
        PageViewController * initialViewController = [self viewCintrollerAtIndex:0];
        
        NSArray * viewControllers = [NSArray arrayWithObjects:initialViewController,nil];
        [_pageController setViewControllers:viewControllers direction:(UIPageViewControllerNavigationDirectionForward) animated:FALSE completion:nil];
        [self addChildViewController:_pageController];
        [self.view addSubview:_pageController.view];
        [_pageController didMoveToParentViewController:self];
        
        
        UILabel *jumpLab = [[UILabel alloc]initWithFrame:CGRectMake(SCREEN_WIDTH / 2.0f + 135.0f - 150.0f, 10.0f, 30.0f, 30.0f)];
        jumpLab.backgroundColor = [UIColor clearColor];
        jumpLab.font = [UIFont systemFontOfSize:15.0f];
        jumpLab.text = @"转到";
        [self.view addSubview:jumpLab];
        
        //120 = (15 + 60 + 135 + 30) / 2
        _pageTextField = [[UITextField alloc]initWithFrame:CGRectMake(SCREEN_WIDTH / 2.0 + 135 - 120, 12.5f, 60.0f, 25.0f)];
        _pageTextField.returnKeyType = UIReturnKeyDone;
        _pageTextField.delegate = self;
        _pageTextField.textAlignment = NSTextAlignmentCenter;
        _pageTextField.borderStyle = UITextBorderStyleLine;
        _pageTextField.keyboardType = UIKeyboardTypeNumbersAndPunctuation;
        
        [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification  object:nil];
        
        UILabel *backLab = [[UILabel alloc]initWithFrame:CGRectMake(SCREEN_WIDTH / 2.0 + 135 - 120 + 62, 10.0f, 15.0f, 30.0f)];
        backLab.backgroundColor = [UIColor clearColor];
        backLab.font = [UIFont systemFontOfSize:15.0f];
        backLab.text = @"页";
        [self.view addSubview:backLab];
        
        UIButton *goBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        goBtn.frame = CGRectMake(SCREEN_WIDTH / 2.0 + 135 - 120 + 62 + 15, 10.0, 30, 30);
        [goBtn setImage:[UIImage imageNamed:@"icon_go"] forState:UIControlStateNormal];
        [goBtn setImage:[UIImage imageNamed:@"icon_go_pre"] forState:UIControlStateHighlighted];
        [goBtn addTarget:self action:@selector(keyboardWillHide:) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:goBtn];
        
        [self.view addSubview:_pageTextField];
        
    } failure:^(NSError *error){

    } networkerror:^(NSString *networkstring){

    }];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [_pageTextField resignFirstResponder];
    return TRUE;
}

-(void)keyboardWillHide:(NSNotification *)note
{
    if(_pageTextField.text.length == 0)
    {
        [_pageTextField resignFirstResponder];
        return;
    }
    if([self isPureNumandCharacters:_pageTextField.text])
    {
        int pageInt = [_pageTextField.text intValue] - 1 ;
        if(pageInt >= [_dataArray count] || pageInt < 0)
        {
            MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:TRUE];
            hud.mode = MBProgressHUDModeText;
            hud.labelText = @"不在范围内，无法跳转";
            hud.labelFont = [UIFont systemFontOfSize:13.0f];
            [hud hide:TRUE afterDelay:1.0f];

            return;
        }
        else
        {
            [_pageController setViewControllers:[NSArray arrayWithObject:[self viewCintrollerAtIndex:pageInt]] direction:(_mIndex > pageInt ? UIPageViewControllerNavigationDirectionReverse : UIPageViewControllerNavigationDirectionForward) animated:( _mIndex == pageInt ? FALSE : TRUE ) completion:^(BOOL finished){ _mIndex = pageInt; }];
        }
        
    }
    else
    {
        MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:TRUE];
        hud.mode = MBProgressHUDModeText;
        hud.labelText = @"含有非法字符";
        hud.labelFont = [UIFont systemFontOfSize:13.0f];
        [hud hide:TRUE afterDelay:1.0f];
    }

}

- (BOOL)isPureNumandCharacters:(NSString *)string
{
    string = [string stringByTrimmingCharactersInSet:[NSCharacterSet decimalDigitCharacterSet]];
    if(string.length > 0)
    {
        return NO;
    }
    return YES;
}

- (PageViewController *)viewCintrollerAtIndex:(NSUInteger)index{
    if ([_dataArray count] == 0 || (index >= [_dataArray count])) {
        return nil;
    }
    PageViewController * pageViewController = [[PageViewController alloc]init];
    pageViewController.urlString = [_dataArray objectAtIndex:index];
    pageViewController.indexInt = index;
    pageViewController.accountInt = [_dataArray count];
    return pageViewController;

}

- (NSUInteger)indexOfViewController:(PageViewController*)viewController{
    return  [_dataArray indexOfObject:viewController.urlString];
}

- (void)pageViewController:(UIPageViewController *)pageViewController didFinishAnimating:(BOOL)finished previousViewControllers:(NSArray *)previousViewControllers transitionCompleted:(BOOL)completed
{
    if(_mIndex == 0 || _mIndex > [_dataArray count])
    {
        return;
    }
}

- (UIViewController *)pageViewController:(UIPageViewController *)pageViewController viewControllerAfterViewController:(UIViewController *)viewController{
    NSUInteger index = [self indexOfViewController:(PageViewController *)viewController];
    if (index == NSNotFound) {
        return nil;
    }
    index++;
    _mIndex = index;
    if (index == [_dataArray count]) {
        return nil;
    }
    return [self viewCintrollerAtIndex:index];
}
- (UIViewController *)pageViewController:(UIPageViewController *)pageViewController viewControllerBeforeViewController:(UIViewController *)viewController{
    NSUInteger index = [self indexOfViewController:(PageViewController *)viewController];
    if (index == 0 || (index == NSNotFound)) {
        return nil;
    }
    index --;
    _mIndex = index;
    return [self viewCintrollerAtIndex:index];
}

- (void)buttonBackTapped:(id)sender
{
    [[UIApplication sharedApplication]setStatusBarHidden:FALSE];
    [self.navigationController popViewControllerAnimated:TRUE];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
